using System;
using System.Collections.Generic;
using System.Text;

namespace OnlinePlots.Diagrams
{
    /// <summary>
    /// Represents the collection of diagram elements
    /// </summary>
    /// <typeparam name="T">Type of diagram elements</typeparam>
    public class DiagramElementCollection<T> : IList<T> where T : DiagramElement
    {
        private DiagramElement parentElement;
        private List<T> items = new List<T>();

        internal DiagramElementCollection(DiagramElement parentElement)
        {
            this.parentElement = parentElement;
        }

        public int IndexOf(T item)
        {
            return items.IndexOf(item);
        }

        public void Insert(int index, T item)
        {
            item.BindToDiagramElement(parentElement);
            items.Insert(index, item);
        }

        public void RemoveAt(int index)
        {
            if(index < items.Count)
            {
                items[index].Unbind();
                items.RemoveAt(index);
            }
        }

        public T this[int index]
        {
            get
            {
                return items[index];
            }
            set
            {
                items[index].Unbind();
                items[index] = value;
                items[index].BindToDiagramElement(parentElement);
            }
        }

        public void Add(T item)
        {
            item.BindToDiagramElement(parentElement);
            items.Add(item);
        }

        public void Clear()
        {
            foreach(T item in items)
            {
                item.Unbind();
            }
            items.Clear();
        }

        public bool Contains(T item)
        {
            return items.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            items.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return items.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(T item)
        {
            item.Unbind();
            if (items.Remove(item))
            {
                item.Unbind();
                return true;
            }
            return false;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return items.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return items.GetEnumerator();
        }
    }
}
